<template>
  <div class="time-select-page">
    <!-- 顶部导航栏 -->
    <div class="header">
      <div class="header-content">
        <div class="back-btn" @click="$router.go(-1)">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M15 18l-6-6 6-6"/>
          </svg>
        </div>
        <div class="header-title">第四步: 选择时间</div>
        <div class="home-btn" @click="$router.push('/')">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#fff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
            <path d="M3 9l9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>
            <polyline points="9,22 9,12 15,12 15,22"/>
          </svg>
        </div>
      </div>
    </div>

    <!-- 页面内容 -->
    <div class="content">
      <!-- 医生信息 -->
      <div class="doctor-info" v-if="selectedDoctor">
        <div class="doctor-avatar">
          <img 
            :src="selectedDoctor.avatar" 
            :alt="selectedDoctor.name"
            @error="handleImageError"
          />
        </div>
        <div class="doctor-details">
          <h3 class="doctor-name">{{ selectedDoctor.name }}</h3>
          <p class="doctor-department">{{ selectedDoctor.department }}</p>
          <p class="doctor-hospital">{{ selectedDoctor.hospital }}</p>
        </div>
      </div>

      <!-- 日期选择 -->
      <div class="date-section">
        <div class="section-header">
          <h2>就诊日期</h2>
          <div class="month-selector" @click="showMonthPicker = true">
            <span>{{ currentMonthDisplay }}</span>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <polyline points="6,9 12,15 18,9"/>
            </svg>
          </div>
        </div>
        
        <div class="date-list">
          <div 
            v-for="date in availableDates" 
            :key="date.key"
            class="date-item"
            :class="{ 'selected': selectedDate === date.key }"
            @click="selectDate(date.key)"
          >
            <div class="day-name">{{ date.dayName }}</div>
            <div class="day-number">{{ date.dayNumber }}</div>
          </div>
        </div>
      </div>

      <!-- 时间选择 -->
      <div class="time-section">
        <h2>就诊时间</h2>
        <div class="time-grid">
          <div 
            v-for="timeSlot in availableTimeSlots" 
            :key="timeSlot.key"
            class="time-slot"
            :class="{ 'selected': selectedTime === timeSlot.key }"
            @click="selectTime(timeSlot.key)"
          >
            {{ timeSlot.display }}
          </div>
        </div>
      </div>
    </div>

    <!-- 底部按钮 -->
    <div class="bottom-button">
      <button 
        class="next-btn" 
        :class="{ 'disabled': !canProceed }"
        @click="goToNextStep"
        :disabled="!canProceed"
      >
        下一步
      </button>
    </div>

    <!-- 月份选择器模态框 -->
    <div v-if="showMonthPicker" class="month-picker-overlay" @click="showMonthPicker = false">
      <div class="month-picker" @click.stop>
        <div class="picker-header">
          <h3>选择月份</h3>
          <button class="close-btn" @click="showMonthPicker = false">
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
              <line x1="18" y1="6" x2="6" y2="18"/>
              <line x1="6" y1="6" x2="18" y2="18"/>
            </svg>
          </button>
        </div>
        <div class="month-grid">
          <div 
            v-for="month in availableMonths" 
            :key="month.key"
            class="month-item"
            :class="{ 'selected': currentMonth === month.key }"
            @click="selectMonth(month.key)"
          >
            {{ month.display }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

interface Doctor {
  _id: string
  name: string
  department: string
  avatar: string
  hospital: string
}

interface DateItem {
  key: string
  dayName: string
  dayNumber: string
  date: Date
}

interface TimeSlot {
  key: string
  display: string
  startTime: string
  endTime: string
}

interface MonthItem {
  key: string
  display: string
  date: Date
}

const selectedDoctor = ref<Doctor | null>(null)
const selectedDate = ref<string>('')
const selectedTime = ref<string>('')
const showMonthPicker = ref(false)

// 当前月份
const currentMonth = ref<string>('')
const currentMonthDisplay = ref<string>('')

// 获取当前时间
const now = new Date()
const currentDate = new Date(now.getFullYear(), now.getMonth(), now.getDate())
const currentHour = now.getHours()

// 生成可用日期（从今天开始，未来30天）
const availableDates = computed(() => {
  const dates: DateItem[] = []
  const dayNames = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  
  for (let i = 0; i < 30; i++) {
    const date = new Date(currentDate)
    date.setDate(date.getDate() + i)
    
    const dayName = dayNames[date.getDay()]
    const dayNumber = date.getDate().toString()
    const key = date.toISOString().split('T')[0]
    
    dates.push({
      key,
      dayName,
      dayNumber,
      date
    })
  }
  
  return dates
})

// 生成可用时间段
const availableTimeSlots = computed(() => {
  const slots: TimeSlot[] = []
  const baseSlots = [
    { start: '08:00', end: '09:00', display: '8:00 AM - 9:00 AM' },
    { start: '09:00', end: '10:00', display: '9:00 AM - 10:00 AM' },
    { start: '10:00', end: '11:00', display: '10:00 AM - 11:00 AM' },
    { start: '11:00', end: '12:00', display: '11:00 AM - 12:00 PM' },
    { start: '14:00', end: '15:00', display: '2:00 PM - 3:00 PM' },
    { start: '15:00', end: '16:00', display: '3:00 PM - 4:00 PM' },
    { start: '16:00', end: '17:00', display: '4:00 PM - 5:00 PM' },
    { start: '17:00', end: '18:00', display: '5:00 PM - 6:00 PM' }
  ]
  
  // 如果是今天，只显示当前时间之后的时间段
  const isToday = selectedDate.value === currentDate.toISOString().split('T')[0]
  
  baseSlots.forEach(slot => {
    const slotHour = parseInt(slot.start.split(':')[0])
    
    // 如果是今天，只显示当前时间之后的时间段
    if (isToday && slotHour <= currentHour) {
      return
    }
    
    slots.push({
      key: `${selectedDate.value}-${slot.start}`,
      display: slot.display,
      startTime: slot.start,
      endTime: slot.end
    })
  })
  
  return slots
})

// 生成可用月份
const availableMonths = computed(() => {
  const months: MonthItem[] = []
  const monthNames = ['一月', '二月', '三月', '四月', '五月', '六月', 
                     '七月', '八月', '九月', '十月', '十一月', '十二月']
  
  for (let i = 0; i < 12; i++) {
    const date = new Date(now.getFullYear(), now.getMonth() + i, 1)
    const key = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
    const display = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}`
    
    months.push({
      key,
      display,
      date
    })
  }
  
  return months
})

// 是否可以继续
const canProceed = computed(() => {
  return selectedDate.value && selectedTime.value
})

// 选择日期
const selectDate = (dateKey: string) => {
  selectedDate.value = dateKey
  selectedTime.value = '' // 重置时间选择
}

// 选择时间
const selectTime = (timeKey: string) => {
  selectedTime.value = timeKey
}

// 选择月份
const selectMonth = (monthKey: string) => {
  currentMonth.value = monthKey
  currentMonthDisplay.value = monthKey
  showMonthPicker.value = false
  
  // 更新当前月份显示
  const [year, month] = monthKey.split('-')
  currentMonthDisplay.value = `${year}-${month}`
}

// 下一步
const goToNextStep = () => {
  if (!canProceed.value) {
    showToast('请选择就诊日期和时间')
    return
  }
  
  // 保存选择的时间
  const appointmentData = {
    date: selectedDate.value,
    time: selectedTime.value,
    doctor: selectedDoctor.value
  }
  
  localStorage.setItem('appointmentData', JSON.stringify(appointmentData))
  
  // 跳转到就诊人选择页面
  router.push('/patient-select')
}

// 轻提示
const showToast = (message: string) => {
  const toast = document.createElement('div')
  toast.className = 'toast-message'
  toast.textContent = message
  document.body.appendChild(toast)
  
  setTimeout(() => toast.classList.add('show'), 10)
  setTimeout(() => {
    toast.classList.remove('show')
    setTimeout(() => {
      if (document.body.contains(toast)) {
        document.body.removeChild(toast)
      }
    }, 300)
  }, 3000)
}

// 图片加载错误处理
const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.src = ''
}

onMounted(() => {
  // 获取选中的医生信息
  const savedDoctor = localStorage.getItem('selectedDoctor')
  if (savedDoctor) {
    selectedDoctor.value = JSON.parse(savedDoctor)
  }
  
  // 设置默认选择今天
  selectedDate.value = currentDate.toISOString().split('T')[0]
  
  // 设置当前月份
  const currentMonthKey = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
  currentMonth.value = currentMonthKey
  currentMonthDisplay.value = currentMonthKey
})
</script>

<style scoped>
.time-select-page {
  min-height: 100vh;
  background: #f8f9fa;
  padding-bottom: 100px;
}

.header {
  background: #1877F2;
  padding: 0 20px;
  padding-top: env(safe-area-inset-top);
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 56px;
}

.back-btn, .home-btn {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  border-radius: 8px;
  transition: all 0.2s;
}

.back-btn:hover, .home-btn:hover {
  background: rgba(255, 255, 255, 0.1);
}

.header-title {
  color: #fff;
  font-size: 18px;
  font-weight: 600;
  flex: 1;
  text-align: center;
}

.content {
  padding: 20px;
}

/* 医生信息 */
.doctor-info {
  background: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.doctor-avatar {
  width: 60px;
  height: 60px;
  border-radius: 50%;
  overflow: hidden;
  background: linear-gradient(135deg, #00D4FF 0%, #5B73FF 100%);
  display: flex;
  align-items: center;
  justify-content: center;
}

.doctor-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.doctor-details {
  flex: 1;
}

.doctor-name {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 4px 0;
}

.doctor-department {
  font-size: 14px;
  color: #666;
  margin: 0 0 2px 0;
}

.doctor-hospital {
  font-size: 12px;
  color: #999;
  margin: 0;
}

/* 日期选择 */
.date-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.section-header h2 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0;
}

.month-selector {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
}

.month-selector:hover {
  background: #e9ecef;
}

.date-list {
  display: flex;
  gap: 12px;
  overflow-x: auto;
  padding-bottom: 8px;
}

.date-item {
  min-width: 60px;
  height: 80px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  border: 2px solid transparent;
}

.date-item:hover {
  background: #e9ecef;
}

.date-item.selected {
  background: #1877F2;
  color: white;
  border-color: #1877F2;
}

.day-name {
  font-size: 12px;
  margin-bottom: 4px;
}

.day-number {
  font-size: 18px;
  font-weight: 600;
}

/* 时间选择 */
.time-section {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.time-section h2 {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin: 0 0 16px 0;
}

.time-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
  gap: 12px;
}

.time-slot {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  border: 2px solid transparent;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.time-slot:hover {
  background: #e9ecef;
}

.time-slot.selected {
  background: #1877F2;
  color: white;
  border-color: #1877F2;
}

/* 底部按钮 */
.bottom-button {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 16px;
  background: #fff;
  border-top: 1px solid #f0f0f0;
  z-index: 100;
}

.next-btn {
  width: 100%;
  height: 48px;
  background: #1877F2;
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.next-btn:hover:not(.disabled) {
  background: #1565c0;
}

.next-btn.disabled {
  background: #ccc;
  color: #999;
  cursor: not-allowed;
}

/* 月份选择器 */
.month-picker-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.month-picker {
  background: white;
  border-radius: 12px;
  width: 90%;
  max-width: 400px;
  max-height: 80%;
  overflow: hidden;
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.2);
}

.picker-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.picker-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  border-radius: 4px;
  transition: background 0.2s;
}

.close-btn:hover {
  background: #f0f0f0;
}

.month-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 1px;
  padding: 20px;
}

.month-item {
  height: 48px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f8f9fa;
  cursor: pointer;
  transition: all 0.2s;
  font-size: 14px;
  font-weight: 500;
  color: #333;
}

.month-item:hover {
  background: #e9ecef;
}

.month-item.selected {
  background: #1877F2;
  color: white;
}

/* 轻提示 */
.toast-message {
  position: fixed;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 12px 24px;
  border-radius: 8px;
  font-size: 14px;
  font-weight: 500;
  z-index: 10000;
  opacity: 0;
  transition: opacity 0.3s ease-in-out;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  white-space: nowrap;
}

.toast-message.show {
  opacity: 1;
}

/* 响应式设计 */
@media (max-width: 480px) {
  .content {
    padding: 16px;
  }
  
  .date-list {
    gap: 8px;
  }
  
  .date-item {
    min-width: 50px;
    height: 70px;
  }
  
  .time-grid {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 8px;
  }
  
  .time-slot {
    height: 44px;
    font-size: 13px;
  }
}
</style> 